package org.baygo.view.api.impl;

import com.babygo.transport.api.FileClientOperator;
import com.babygo.transport.api.FileServerOperator;
import com.babygo.view.api.ViewOperator;
import org.baygo.view.MainFrame;
import org.baygo.view.api.listener.ConnectedClientButtonActionListener;
import org.baygo.view.api.listener.mycomponent.MyButton;

import javax.swing.*;
import java.io.File;
import java.util.HashMap;

public class MyViewOperator implements ViewOperator{

	private static MyViewOperator myViewOperator = new MyViewOperator();
	private static HashMap<String, MyButton> connectButtons = new HashMap<String, MyButton>();

	public void addNewConnectButoon(String ip, String port, MyButton button){
		connectButtons.put(ip + ":" + port, button);
	}

	public MyButton getButton(String ip, String port){
		return connectButtons.get(ip + ":" + port);
	}
	
	public static MyViewOperator getMyOperator(){
		return myViewOperator;
	}

	public boolean receiveNewConnect(String adress) {
		int result = JOptionPane.showConfirmDialog(MainFrame.getMainFrame(), 
				"是否允许来自" + adress + "的连接", "连接请求", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
		return result==0;
	}

	public File getFile(){
		 JFileChooser jfc=new JFileChooser();
		 int i = jfc.showOpenDialog(MainFrame.getMainFrame());
		 if (i==JFileChooser.APPROVE_OPTION){
			 return jfc.getSelectedFile();
		 } else return new File("");
	}

	public void writeLog(String log) {
		MainFrame.getPanel().getLogArea().append(log+"\n");
	}

	public void processUpdate(int index) {
		// TODO Auto-generated method stub
		
	}

	public void remotServerConnectClosed(String ip, String port) {
		connectButtons.get(ip + ":" + port).turnRed();
	}

	public void remotClientClosed(String ip, String port) {
		connectButtons.get(ip + ":" + port).turnGray();
	}

	public void acceptNewClientConnector(String ip, String port) {
		MyButton button = MainFrame.getPanel().openNewConnectButton(ip+" "+ port, false).turnCyan();
		button.addMouseListener(new ConnectedClientButtonActionListener(button, ip, port));
		addNewConnectButoon(ip, port, button);
	}

	public FileServerOperator getServerOper() {
		return ConnectedClientButtonActionListener.getFileServer();
	}

	public FileClientOperator getClientOper() {
		// TODO Auto-generated method stub
		return null;
	}

	public File saveFile() {
		JFileChooser jfc=new JFileChooser("保存文件");
		int i = jfc.showSaveDialog(MainFrame.getMainFrame());
		if (i==JFileChooser.APPROVE_OPTION){
			return jfc.getSelectedFile();
		} else return new File("");
	}

	public boolean acceptPushFile(String ip, String fileName) {
		int result = JOptionPane.showConfirmDialog(MainFrame.getMainFrame(), 
				"是否允许来自" + ip + "的发送的文件:" + fileName, "是否接受文件", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
		return result==0;
	}

	public File getTheFileNeedToSend() {
		// TODO Auto-generated method stub
		return null;
	}

	public File getTheSaveFile() {
		// TODO Auto-generated method stub
		return null;
	}
}